package com.example.knowledgeget1.KnowtController;

import com.example.knowledgeget1.Common.HttpStatusEnum;
import com.example.knowledgeget1.Common.ResponseResult;
import com.example.knowledgeget1.KnowtCommon.Entity.KnowStatus;
import com.example.knowledgeget1.KnowtCommon.Service.KnowStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/knowstatus")
public class KnowStatusController {
    @Autowired
    private KnowStatusService knowStatusService;


    @GetMapping("/get/{stuId}/{courseId}")
    public ResponseResult getKnowStatusByCourseId(@PathVariable Long stuId, @PathVariable Long courseId) {
        List<KnowStatus> knowStatuses = knowStatusService.getKnowStatusByStuAndCourse(stuId, courseId);

        List<Long> learnedKnowIds = knowStatuses.stream()
                .filter(KnowStatus::getStatus)
                .map(status -> status.getId().getKnowId())
                .collect(Collectors.toList());

        List<Long> unlearnedKnowIds = knowStatuses.stream()
                .filter(status -> !status.getStatus())
                .map(status -> status.getId().getKnowId())
                .collect(Collectors.toList());

        List<String> learnedKnowNames = knowStatusService.getKnowledgeNamesByIds(learnedKnowIds);
        List<String> unlearnedKnowNames = knowStatusService.getKnowledgeNamesByIds(unlearnedKnowIds);

        Map<String, List<String>> statusMap = new HashMap<>();
        statusMap.put("learned", learnedKnowNames);
        statusMap.put("unlearned", unlearnedKnowNames);

        if (learnedKnowIds.isEmpty() && unlearnedKnowIds.isEmpty()) {
            return ResponseResult.fail(HttpStatusEnum.NOT_FOUND);
        }
        return ResponseResult.success(statusMap);
    }

    @PostMapping("/learn")
    public ResponseResult learnKnowledge(@RequestBody Map<String, Object> request) {
        knowStatusService.learnKnowledge(request);
        return ResponseResult.success();
    }

    @PostMapping("/unlearn")
    public ResponseResult unlearnKnowledge(@RequestBody Map<String, Object> request) {
        knowStatusService.unlearnKnowledge(request);
        return ResponseResult.success();
    }
}
